import React, { useEffect, useState, Component } from 'react';
import {
  Modal,
  Form,
  Input,
  Checkbox,
  DatePicker,
  Select,
  Button,
  message,
  Upload,
} from 'antd';
import { useLocation } from 'umi';
import AMapLoader from '@amap/amap-jsapi-loader';
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import { IDomEditor } from '@wangeditor/editor';
import { connect, history } from 'umi';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';

import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import './index.less';
//上传
const getBase64 = (img: RcFile, callback: (url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
};
//上传之前
const beforeUpload = (file: RcFile) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('必须是JPG/PNG');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片必须小于2MB!');
  }
  return isJpgOrPng && isLt2M;
};
//类组件
function editDetail(props: any) {
  let map;
  //   console.log(history.location);
  const [form] = Form.useForm();
  let location = useLocation();
  let obj = location.state.state.record;
  useEffect(() => {
    // fang_houseDetail({ id: history.location.state?.id }).then((res) => {
    //   setobj(res.data);
    // });
    form.setFieldsValue(obj);
  }, []);
  // 地图
  let Map = () => {
    setIsModalOpen(true);
    AMapLoader.load({
      key: '3d35df99e38c9ca94a3340585e82b1c8', // 申请好的Web端开发者Key，首次调用 load 时必填
      version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: [''], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    })
      .then((AMap: any) => {
        map = new AMap.Map('container', {
          //设置地图容器id
          viewMode: '3D', //是否为3D地图模式
          zoom: 5, //初始化地图级别
          center: [obj.lng, obj.lat], //初始化地图中心点位置
        });
      })
      .catch((e: any) => {
        console.log(e);
      });
  };
  //弹出框
  const [isModalOpen, setIsModalOpen] = useState(false);
  const { Search } = Input;
  const { TextArea } = Input;
  //富文本
  // editor 实例
  const [editor, setEditor] = useState<IDomEditor | null>(null); // TS 语法
  // 编辑器内容
  const [html, setHtml] = useState('<p>hello</p>');
  const onFinish = (values: any) => {
    values.id = obj.id;
    console.log('Successsss:', values);
    props.dispatch({
      type: 'index/EDIT_List',
      payload: values,
    });
    history.push('/homes/properties/management/Propertylist');
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };
  //上传图片
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();

  const handleChange: UploadProps['onChange'] = (
    info: UploadChangeParam<UploadFile>,
  ) => {
    if (info.file.status === 'uploading') {
      console.log('handleChange');
      setLoading(true);
      return;
    }

    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj as RcFile, (url) => {
        setLoading(false);
        // console.log('====================================');
        // console.log(url);
        // console.log('====================================');
        setImageUrl(url);
      });
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );
  return (
    <div>
      <div>
        <Form
          form={form}
          style={{ display: 'flex' }}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <div style={{ width: '430px' }}>
            <Form.Item
              label="楼盘名称"
              name="title"
              style={{ width: '300px' }}
              rules={[
                { required: true, message: 'Please input your username!' },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="楼盘地址"
              name="address"
              style={{ width: '300px' }}
              rules={[
                { required: true, message: 'Please input your username!' },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="开盘时间"
              name="update_time
"
              style={{ display: 'flex' }}
            >
              <DatePicker />
              <Input style={{ width: '150px', marginLeft: '10px' }} />
            </Form.Item>
            <Form.Item
              label="售楼电话"
              name="create_time"
              style={{ width: '350px', display: 'flex' }}
              rules={[
                { required: true, message: 'Please input your username!' },
              ]}
            >
              <div style={{ display: 'flex' }}>
                <Input style={{ width: '230px', marginRight: '5px' }} />转
                <Input style={{ width: '120px', marginLeft: '5px' }} />
              </div>
            </Form.Item>
            <Form.Item
              label="开发科"
              style={{ width: '300px' }}
              rules={[
                { required: true, message: 'Please input your username!' },
              ]}
            >
              <Input />
            </Form.Item>
          </div>
          <div>
            <Form.Item
              label="均价"
              name="username"
              style={{ width: '300px', display: 'flex' }}
              rules={[
                { required: true, message: 'Please input your username!' },
              ]}
            >
              <div style={{ width: '300px', display: 'flex' }}>
                <Input style={{ width: '100px', marginRight: '10px' }} />
                <Select style={{ width: '145px' }}>
                  <Select.Option value="元/m²">元/m²</Select.Option>
                  <Select.Option value="万/套">万/套</Select.Option>
                </Select>
              </div>
            </Form.Item>
            <Form.Item label="售楼处地址" style={{ width: '300px' }}>
              <Input />
            </Form.Item>
            <Form.Item label="交房时间" style={{ display: 'flex' }}>
              <DatePicker />
              <Input style={{ width: '150px', marginLeft: '10px' }} />
            </Form.Item>
            <Form.Item label="预售证号" style={{ width: '300px' }}>
              <Input />
            </Form.Item>
            <Form.Item
              label="地图坐标"
              style={{ width: '300px' }}
              rules={[
                { required: true, message: 'Please input your username!' },
              ]}
            >
              <Search
                style={{ width: '350px' }}
                value={`${obj.lng},${obj.lat}`}
                enterButton="标注位置"
                onSearch={(e: any) => {
                  Map();
                }}
              />
            </Form.Item>
          </div>
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit">
              Submit
            </Button>
          </Form.Item>
        </Form>
      </div>
      <p>
        <span>优惠楼盘</span>
        <Checkbox
          style={{ marginLeft: '10px' }}
          onChange={(e: any) => {}}
        ></Checkbox>
      </p>
      <p>
        <span>优惠内容</span>
        <TextArea style={{ width: '80%' }} rows={5} maxLength={100} />
      </p>
      <Upload
        name="avatar"
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        action="http://fangadmin.shbwyz.com/house/ajaxuploadimg.html"
        beforeUpload={beforeUpload}
        onChange={handleChange}
      >
        {imageUrl ? (
          <img src={imageUrl} alt="avatar" style={{ width: '100%' }} />
        ) : (
          uploadButton
        )}
      </Upload>
      <Modal
        width={1000}
        height={600}
        footer={null}
        open={isModalOpen}
        onCancel={() => {
          setIsModalOpen(false);
        }}
      >
        <div
          id="container"
          className="map"
          style={{ width: '100%', height: '800px' }}
        ></div>
      </Modal>
      <>
        <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
          <Toolbar
            editor={editor}
            mode="default"
            style={{ borderBottom: '1px solid #ccc' }}
          />
          <Editor
            value={html}
            onCreated={setEditor}
            onChange={(editor) => setHtml(editor.getHtml())}
            mode="default"
            style={{ height: '500px', overflowY: 'hidden' }}
          />
        </div>
        {html}
        {/* <div style={{ marginTop: '15px' }}>{html}</div> */}
      </>
    </div>
  );
}
const mapStateToProps = (state: any) => {
  // console.log('====================================');
  // console.log(state, 'state');
  // console.log('====================================');
};
export default connect(mapStateToProps)(editDetail);
